package cn.kent.simple;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 104.二叉树的最大深度
 * bfs和dfs
 */
public class MaxDepth {
    public static void main(String[] args) {
        TreeNode head = new TreeNode(0);
        head.left = new TreeNode(1);
        head.right = new TreeNode(2);
        head.left.left = new TreeNode(3);
        head.left.right = new TreeNode(3);
        int res = maxDepth2(head);
        System.out.println(res);
    }

    /**
     * dfs
     */
    private static int maxDepth(TreeNode head) {
        if (head == null) {
            return 0;
        } else {
            final int dfsLeft = maxDepth(head.left);
            final int dfsRight = maxDepth(head.right);
            return Math.max(dfsLeft, dfsRight) + 1;
        }
    }

    /**
     * bfs
     */
    private static int maxDepth2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        final Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int ans = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size > 0) {
                final TreeNode node = queue.poll();
                if (node.left != null)
                    queue.offer(node.left);
                if (node.right != null)
                    queue.offer(node.right);
                size--;
            }
            ans++;
        }
        return ans;
    }


    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
